<?php
declare (strict_types=1);

namespace app\index\controller;

use app\common\model\User;
use app\common\model\UserCode;
use think\exception\ValidateException;
use think\facade\View;
use think\response\Json;

class Login extends Base
{
    public function index()
    {
        return View::fetch();
    }

    public function check(): Json
    {
        try {
            $param = $this->request->post('', '', $this->filter);
            $this->validate($param, 'Login');
            $user = User::where(['mobile' => $param['mobile'], 'is_del' => 0])->find();
            if (empty($user)) return json(['code' => -1, 'msg' => '账号不存在']);
            if ($user->password != md5($param['password'])) return json(['code' => -1, 'msg' => '密码错误']);
            if ($user->is_lock) return json(['code' => -1, 'msg' => '账号已冻结']);
            $time = time();
            $token = md5(json_encode($user) . $time . $this->request->ip());
            $user->token = $token;
            $user->last_time = $time;
            $user->last_ip = $this->request->ip();
            $user->save();
            cookie('token', $token);

        } catch (ValidateException $e) {

            return json(['code' => -1, 'msg' => $e->getMessage()]);
        } catch (\Exception $e) {

            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

        return json(['code' => 1, 'msg' => '登录成功', 'token' => $token, 'url' => '/']);
    }

    public function forget()
    {
        if ($this->request->isPost()) {
            $param = $this->request->post('', '', $this->filter);
            try {
                $this->validate($param, 'Forget');
            } catch (ValidateException $e) {
                return json(['code' => -1, 'msg' => $e->getError()]);
            }
            $user = User::where(['mobile' => $param['mobile'], 'is_del' => 0])->find();
            if (!$user) {
                return json(['code' => -1, 'msg' => '该手机号不存在']);
            }
            //校验短信验证码
            $res = UserCode::verifyMsgCode($param['mobile'], $param['captcha'], 'forgetPassword');
            if ($res !== true) {
                return json(['code' => -1, 'msg' => $res]);
            }
            $token = md5(json_encode($user) . time());
            $user->token = $token;
            $type = $param['type'];
            $user->$type = md5($param['password']);
            $user->save();
            $msg = $type == 'password' ? '登录密码' : '支付密码';

            return json(['code' => 1, 'msg' => '您的' . $msg . '已找回，请牢记您的新密码', 'url' => url('login/index')->build()]);
        }

        return View::fetch();
    }
}